package top.hcode.hoj.service.admin.course;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.hcode.hoj.dao.LinkLoader;
import top.hcode.hoj.dao.course.CourseDao;
import top.hcode.hoj.dao.course.CourseSectionDao;
import top.hcode.hoj.dao.course.LessonDao;
import top.hcode.hoj.exception.ServiceException;
import top.hcode.hoj.pojo.dto.AdminQueryCourseDTO;
import top.hcode.hoj.pojo.entity.course.Course;
import top.hcode.hoj.pojo.entity.course.CourseSection;
import top.hcode.hoj.pojo.entity.course.Lesson;

/**
 * @author orangej
 * @since 2024/12/18
 */
@Component
public class AdminCourseService {
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CourseSectionDao sectionDao;
    @Autowired
    private LessonDao lessonDao;
    @Autowired
    private LinkLoader cascadeLoader;

    public IPage<Course> getCourseList(AdminQueryCourseDTO dto) {
        IPage<Course> pager = new Page<>(dto.getCurrentPage(), dto.getLimit());

        QueryWrapper<Course> query = Wrappers.query();
        String keyword = dto.getKeyword();
        if (Strings.isNotBlank(keyword)) {
            query.and(c -> c.like("course_name", keyword).or().like("description", keyword));
        }

        pager = courseDao.page(pager, query);
        cascadeLoader.loadTags(pager.getRecords());
        return pager;
    }

    public Course saveCourse(Course dbo) {
        courseDao.saveOrUpdate(dbo);
        return dbo;
    }

    public void deleteCourse(Long id) {
        if (sectionDao.count(new QueryWrapper<CourseSection>().eq("course_id", id)) > 0) {
            throw new ServiceException("请先删除章节和视频信息");
        }
        if (lessonDao.count(new QueryWrapper<Lesson>().eq("course_id", id)) > 0) {
            throw new ServiceException("情先删除视频信息");
        }

        courseDao.removeById(id);
    }
}
